{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Reconstrunct Binary Tree from Preorder and Inorder Traversals\n",
    "\n",
    "[原题](https://mp.weixin.qq.com/s/qkK7fvCNBVlvCzXHJfPccA)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "You are given the preorder and inorder traversals of a binary tree in the form of arrays. Write a function that reconstructs the tree represented by these traversals."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example\n",
    "\n",
    "```text\n",
    "Pre-Order Traversal: [a, b, d, e, c, f, g]\n",
    "In-Order Traversal: [d, b, e, a, f, c, g]\n",
    "\n",
    "Return (Level Traversal): 'abcdefg'\n",
    "```\n",
    "\n",
    "The binary tree should be constructed like this:\n",
    "\n",
    "```text\n",
    "#      a\n",
    "#    /   \\\n",
    "#   b     c\n",
    "#  / \\   / \\\n",
    "# d   e f   g\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "''' Packages Imports '''\n",
    "from collections import deque"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node(object):\n",
    "    ''' Class Definitions '''\n",
    "    \n",
    "    def __init__(self, value):\n",
    "        ''' Constructor '''\n",
    "        self.value = value\n",
    "        self.left = None\n",
    "        self.right = None\n",
    "    \n",
    "    def __str__(self):\n",
    "        ''' Level-Order Traversal '''\n",
    "        q = deque()\n",
    "        q.append(self)\n",
    "        result = ''\n",
    "        while len(q):\n",
    "            n = q.popleft()\n",
    "            result += n.value\n",
    "            if n.left:\n",
    "                q.append(n.left)\n",
    "            if n.right:\n",
    "                q.append(n.right)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "def reconstruct(preorder: list, inorder: list):\n",
    "    '''\n",
    "    Construct a binary tree with its pre-order and in-order traversal\n",
    "    '''\n",
    "    \n",
    "    # If one of these two lists is empty,\n",
    "    # It can't construct a binary tree.\n",
    "    if len(preorder) == 0 or len(inorder) == 0:\n",
    "        return None\n",
    "    \n",
    "    # The head node of the tree is the\n",
    "    # first element of pre-order traversal.\n",
    "    head = Node(preorder[0])\n",
    "    \n",
    "    # Split the in-order traversal to 2 parts.\n",
    "    middle = inorder.index(preorder[0])\n",
    "    \n",
    "    # Construct their subtrees recursively.\n",
    "    head.left = reconstruct(preorder[1:middle + 1], inorder[:middle])\n",
    "    head.right = reconstruct(preorder[middle + 1:], inorder[middle + 1:])\n",
    "    \n",
    "    # Return the head node.\n",
    "    return head"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "abcdefg\n"
     ]
    }
   ],
   "source": [
    "tree = reconstruct(\n",
    "    ['a', 'b', 'd', 'e', 'c', 'f', 'g'],\n",
    "    ['d', 'b', 'e', 'a', 'f', 'c', 'g']\n",
    ")\n",
    "print(tree)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Notes\n",
    "\n",
    "If we only know one of the preorder traversal or the inorder traversal, the generated binary tree is not unique. \n",
    "\n",
    "Preorder traversal goes with `root -> left subtree -> right subtree`, and inorder traversal goes with `left subtree -> root -> right subtree`. With their difference, we can generate a unique binary tree. "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
